package com.note7_12.question2;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Question1 {

	/*
	 * 1：读取products.xml中的商品信息，输出。
	 */
	public List<Product> getProducts() {
		SAXReader reader = new SAXReader();
		List<Product> list = new ArrayList<>();
		try {
			Document doc = reader.read(new File("src/com/note7_12/question2/products.xml"));
			Element root = doc.getRootElement(); // 获取根节点
			System.out.println("根节点为：" + root.getName());
			List<Element> products = root.selectNodes("product");
			for (Element p : products) {
				String factoryaddr = p.attributeValue("factoryaddr");
				String discountstr = p.attributeValue("discount");
				boolean discount = false;
				if (discountstr.equals("true")) {
					discount = true;
				}
				int itemno = Integer.valueOf(p.selectSingleNode("itemno").getText());
				String name = p.selectSingleNode("name").getText();
				double price = Double.valueOf(p.selectSingleNode("price").getText());
				int stockcount = Integer.valueOf(p.selectSingleNode("stockcount").getText());
				String unit = p.selectSingleNode("unit").getText();
				Product product = new Product(factoryaddr, discount, itemno, name, price, stockcount, unit);
				list.add(product);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}
